{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2308b4ae",
   "metadata": {},
   "source": [
    "# 字典\n",
    "\n",
    "https://www.runoob.com/python3/python3-dictionary.html\n",
    "\n",
    "`d = {key1 : value1, key2 : value2, key3 : value3 }`\n",
    "\n",
    "dict 作为 Python 的关键字和内置函数，变量名不建议命名为 `dict`\n",
    "\n",
    "键必须是唯一的，但值则不必。值可以取任何数据类型，但键必须是不可变的，如字符串，数字。\n",
    "\n",
    "## 访问字典里的值\n",
    "\n",
    "`d['key1']`\n",
    "\n",
    "## 增删改\n",
    "\n",
    "```python\n",
    "tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}\n",
    " \n",
    "tinydict['Age'] = 8               # 更新 Age\n",
    "tinydict['School'] = \"菜鸟教程\"  # 添加信息\n",
    "\n",
    "del tinydict['Name'] # 删除键 'Name'\n",
    "tinydict.clear()     # 清空字典\n",
    "del tinydict         # 删除字典\n",
    "```\n",
    "\n",
    "## 字典键的特性\n",
    "\n",
    "字典值可以是任何的 python 对象，既可以是标准的对象，也可以是用户定义的，但键不行。\n",
    "\n",
    "1. 不允许同一个键出现两次。创建时如果同一个键被赋值两次，后一个值会被记住\n",
    "2. 键必须不可变，所以可以用数字，字符串或元组充当，而用列表就不行\n",
    "\n",
    "## 内置函数和方法\n",
    "\n",
    "| 序号 | 函数及描述                                                   | 实例                                                         |\n",
    "| :--- | :----------------------------------------------------------- | :----------------------------------------------------------- |\n",
    "| 1    | len(dict) 计算字典元素个数，即键的总数。                     | `>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> len(tinydict) 3` |\n",
    "| 2    | str(dict) 输出字典，可以打印的字符串表示。                   | `>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> str(tinydict) \"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}\"` |\n",
    "| 3    | type(variable) 返回输入的变量类型，如果变量是字典就返回字典类型。 | `>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> type(tinydict) <class 'dict'>` |\n",
    "\n",
    "\n",
    "\n",
    "| 序号 | 函数及描述                                                   |\n",
    "| :--- | :----------------------------------------------------------- |\n",
    "| 1    | [dict.clear()](https://www.runoob.com/python3/python3-att-dictionary-clear.html) 删除字典内所有元素 |\n",
    "| 2    | [dict.copy()](https://www.runoob.com/python3/python3-att-dictionary-copy.html) 返回一个字典的浅复制 |\n",
    "| 3    | [dict.fromkeys()](https://www.runoob.com/python3/python3-att-dictionary-fromkeys.html) 创建一个新字典，以序列seq中元素做字典的键，val为字典所有键对应的初始值 |\n",
    "| 4    | [dict.get(key, default=None)](https://www.runoob.com/python3/python3-att-dictionary-get.html) 返回指定键的值，如果键不在字典中返回 default 设置的默认值 |\n",
    "| 5    | [key in dict](https://www.runoob.com/python3/python3-att-dictionary-in.html) 如果键在字典dict里返回true，否则返回false |\n",
    "| 6    | [dict.items()](https://www.runoob.com/python3/python3-att-dictionary-items.html) 以列表返回一个视图对象 |\n",
    "| 7    | [dict.keys()](https://www.runoob.com/python3/python3-att-dictionary-keys.html) 返回一个视图对象 |\n",
    "| 8    | [dict.setdefault(key, default=None)](https://www.runoob.com/python3/python3-att-dictionary-setdefault.html) 和get()类似, 但如果键不存在于字典中，将会添加键并将值设为default |\n",
    "| 9    | [dict.update(dict2)](https://www.runoob.com/python3/python3-att-dictionary-update.html) 把字典dict2的键/值对更新到dict里 |\n",
    "| 10   | [dict.values()](https://www.runoob.com/python3/python3-att-dictionary-values.html) 返回一个视图对象 |\n",
    "| 11   | [dict.pop(key[,default\\])](https://www.runoob.com/python3/python3-att-dictionary-pop.html) 删除字典 key（键）所对应的值，返回被删除的值。 |\n",
    "| 12   | [dict.popitem()](https://www.runoob.com/python3/python3-att-dictionary-popitem.html) 返回并删除字典中的最后一对键和值。 |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c17e163",
   "metadata": {},
   "source": [
    "# 集合\n",
    "\n",
    "https://www.runoob.com/python3/python3-set.html\n",
    "\n",
    "集合（set）是一个无序的不重复元素序列。集合中的元素不会重复，并且可以进行交集、并集、差集等常见的集合操作。\n",
    "\n",
    "可以使用大括号 { } 创建集合，元素之间用逗号 , 分隔， 或者也可以使用 set() 函数创建集合。\n",
    "\n",
    "```python\n",
    "set1 = {1, 2, 3, 4}            # 直接使用大括号创建集合\n",
    "set2 = set([4, 5, 6, 7])      # 使用 set() 函数从列表创建集合\n",
    "```\n",
    "\n",
    "## 集合运算\n",
    "\n",
    "```python\n",
    ">>> # 下面展示两个集合间的运算.\n",
    "...\n",
    ">>> a = set('abracadabra')\n",
    ">>> b = set('alacazam')\n",
    ">>> a                                  \n",
    "{'a', 'r', 'b', 'c', 'd'}\n",
    ">>> a - b                              # 集合a中包含而集合b中不包含的元素\n",
    "{'r', 'd', 'b'}\n",
    ">>> a | b                              # 集合a或b中包含的所有元素\n",
    "{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}\n",
    ">>> a & b                              # 集合a和b中都包含了的元素\n",
    "{'a', 'c'}\n",
    ">>> a ^ b                              # 不同时包含于a和b的元素\n",
    "{'r', 'd', 'b', 'm', 'z', 'l'}\n",
    "```\n",
    "\n",
    "![](./image/集合运算.jpg)\n",
    "\n",
    "## 增删\n",
    "\n",
    "```python\n",
    "s.add() # 增加\n",
    "s.update() # 增加\n",
    "s.remove() # 删除，元素不存在报错\n",
    "s.discard() # 删除，元素不存在不报错\n",
    "s.pop() # 随即删除\n",
    "```\n",
    "\n",
    "## 内置函数和方法\n",
    "\n",
    "| 方法                                                         | 描述                                                         |\n",
    "| :----------------------------------------------------------- | :----------------------------------------------------------- |\n",
    "| [add()](https://www.runoob.com/python3/ref-set-add.html)     | 为集合添加元素                                               |\n",
    "| [clear()](https://www.runoob.com/python3/ref-set-clear.html) | 移除集合中的所有元素                                         |\n",
    "| [copy()](https://www.runoob.com/python3/ref-set-copy.html)   | 拷贝一个集合                                                 |\n",
    "| [difference()](https://www.runoob.com/python3/ref-set-difference.html) | 返回多个集合的差集                                           |\n",
    "| [difference_update()](https://www.runoob.com/python3/ref-set-difference_update.html) | 移除集合中的元素，该元素在指定的集合也存在。                 |\n",
    "| [discard()](https://www.runoob.com/python3/ref-set-discard.html) | 删除集合中指定的元素                                         |\n",
    "| [intersection()](https://www.runoob.com/python3/ref-set-intersection.html) | 返回集合的交集                                               |\n",
    "| [intersection_update()](https://www.runoob.com/python3/ref-set-intersection_update.html) | 返回集合的交集。                                             |\n",
    "| [isdisjoint()](https://www.runoob.com/python3/ref-set-isdisjoint.html) | 判断两个集合是否包含相同的元素，如果没有返回 True，否则返回 False。 |\n",
    "| [issubset()](https://www.runoob.com/python3/ref-set-issubset.html) | 判断指定集合是否为该方法参数集合的子集。                     |\n",
    "| [issuperset()](https://www.runoob.com/python3/ref-set-issuperset.html) | 判断该方法的参数集合是否为指定集合的子集                     |\n",
    "| [pop()](https://www.runoob.com/python3/ref-set-pop.html)     | 随机移除元素                                                 |\n",
    "| [remove()](https://www.runoob.com/python3/ref-set-remove.html) | 移除指定元素                                                 |\n",
    "| [symmetric_difference()](https://www.runoob.com/python3/ref-set-symmetric_difference.html) | 返回两个集合中不重复的元素集合。                             |\n",
    "| [symmetric_difference_update()](https://www.runoob.com/python3/ref-set-symmetric_difference_update.html) | 移除当前集合中在另外一个指定集合相同的元素，并将另外一个指定集合中不同的元素插入到当前集合中。 |\n",
    "| [union()](https://www.runoob.com/python3/ref-set-union.html) | 返回两个集合的并集                                           |\n",
    "| [update()](https://www.runoob.com/python3/ref-set-update.html) | 给集合添加元素                                               |\n",
    "| [len()](https://www.runoob.com/python3/python3-string-len.html) | 计算集合元素个数                                             |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33b5afdf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      ",LPdefhinorstuy,LPdefhinorstuy\n"
     ]
    }
   ],
   "source": [
    "# 1. 字符串去重排序\n",
    "str = input()\n",
    "str = set(str)\n",
    "str.discard(' ') # ！！注意，直接调用方法即可，不需要再次赋值\n",
    "# 因为discard和remove等方法是直接修改集合本身，返回值是None，而不是返回一个新的集合\n",
    "# 如果用str = str.discard(' ')， str会变成None\n",
    "\n",
    "str = sorted(str)\n",
    "for s in str:\n",
    "    print(s, end=\"\")\n",
    "print(''.join(str)) # join输出很方便"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d56763b",
   "metadata": {},
   "source": [
    "`sorted(iterable, cmp=None, key=None, reverse=False)`\n",
    "\n",
    "- iterable -- 可迭代对象。\n",
    "- cmp -- 比较的函数，这个具有两个参数，参数的值都是从可迭代对象中取出，此函数必须遵守的规则为，大于则返回1，小于则返回-1，等于则返回0。\n",
    "- key -- 主要是用来进行比较的元素，只有一个参数，具体的函数的参数就是取自于可迭代对象中，指定可迭代对象中的一个元素来进行排序。\n",
    "- reverse -- 排序规则，reverse = True 降序 ， reverse = False 升序（默认）。\n",
    "\n",
    "sort 与 sorted 区别：\n",
    "\n",
    "- sort 是应用在 list 上的方法，sorted 可以对所有可迭代的对象进行排序操作。\n",
    "- list 的 sort 方法返回的是对已经存在的列表进行操作，无返回值，而内建函数 sorted 方法返回的是一个新的 list，而不是在原来的基础上进行的操作。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "53db75ee",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "# 2. 集合添加元素\n",
    "N = int(input())\n",
    "countries = set()\n",
    "for i in range(N):\n",
    "    country = input() # 每一行都输入一个国家的名字\n",
    "    countries.add(country)\n",
    "print(len(countries))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d65101eb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'孙二娘(乒乓)', '卢俊义(足球)', '吴用(足球)', '宋江', '柴进', '鲁智深(足球)', '林冲(乒乓)', '李逵(乒乓)', '史进'}\n"
     ]
    }
   ],
   "source": [
    "# 3. 体育特长标注\n",
    "group = '鲁智深 柴进 宋江 林冲 卢俊义 孙二娘 史进 吴用 李逵'\n",
    "footBallGroup = '吴用 卢俊义 鲁智深' # 足球\n",
    "pingpangGroup = '林冲 孙二娘 李逵' # 乒乓\n",
    "\n",
    "# 通过集合操作，生成覆盖原group的集合，其中每个数据项对应每个人的名字和特长，输出\n",
    "# 不允许使用列表，输出集合中顺序是随机的\n",
    "\n",
    "# 首先全部转化为集合\n",
    "group = set(group.split(\" \"))\n",
    "group_new = set()\n",
    "footBallGroup = set(footBallGroup.split(\" \"))\n",
    "pingpangGroup = set(pingpangGroup.split(\" \"))\n",
    "\n",
    "for name in group:\n",
    "    if name in footBallGroup:\n",
    "        group_new.add(name + \"(足球)\")\n",
    "    elif name in pingpangGroup:\n",
    "        group_new.add(name + \"(乒乓)\")\n",
    "    else:\n",
    "        group_new.add(name)\n",
    "\n",
    "print(group_new)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "4a689f0b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "得票情况： {'卢俊义': 3, '宋江': 3, '吴用': 4, '林冲': 2, '鲁智深': 1, '柴进': 4, '孙二娘': 1, '史进': 1}\n",
      "最高票数： 4\n",
      "最高得票者：吴用 柴进 "
     ]
    }
   ],
   "source": [
    "# 4. 组长选举\n",
    "vote = ['鲁智深','柴进','宋江','吴用','林冲','卢俊义',\n",
    "'柴进','柴进','孙二娘','史进','吴用','卢俊义','柴进',\n",
    "'林冲','宋江','宋江','卢俊义','吴用','吴用']\n",
    "\n",
    "# 1.将每位被提名者的姓名以及得票数分别作为键和值放入一个字典中，并打印输出该字典。\n",
    "# 2.打印输出最高得票数。\n",
    "# 3.打印输出最高得票者，姓名用空格隔开。\n",
    "\n",
    "vote_count = dict()\n",
    "max_vote = 1\n",
    "names = set(vote)\n",
    "for name in names:\n",
    "    vote_count[name] = vote.count(name)\n",
    "    if vote.count(name) > max_vote:\n",
    "        max_vote = vote.count(name)\n",
    "\n",
    "print(\"得票情况：\", vote_count)\n",
    "print(\"最高票数：\", max_vote)\n",
    "print(\"最高得票者：\", end=\"\")\n",
    "for name in names:\n",
    "    if vote_count[name] == max_vote:\n",
    "        print(name, end=\" \")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "dcb08fc3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "发烧级网虫:\n",
      "大黄鸭 102\n",
      "腿脚细 90\n",
      "水蛇腰 116\n",
      "普通网虫:\n",
      "草肥熊 65\n",
      "黄小丫 52\n",
      "胳膊粗 89\n",
      "水桶腰 53\n"
     ]
    }
   ],
   "source": [
    "# 5. 网虫分类\n",
    "nameList={'草肥熊':65,'黄小丫':52,'大黄鸭':102,'胳膊粗':89,\n",
    "          '腿脚细':90,'水蛇腰':116,'水桶腰':53} #网名和时间字典\n",
    "\n",
    "noPass={} # 普通网虫字典初始化\n",
    "Pass={} # 发烧级网虫字典初始化\n",
    "\n",
    "for name, onlineTime in nameList.items(): # 遍历名单的键值对\n",
    "    if onlineTime < 90:\n",
    "        noPass[name] = onlineTime # 添加普通网虫到普通字典\n",
    "    else:\n",
    "        Pass[name] = onlineTime # 添加发烧级网虫到发烧字典\n",
    "\n",
    "print('发烧级网虫:')\n",
    "for name, onlineTime in Pass.items(): # 遍历发烧级网虫的键值对\n",
    "    print(name, onlineTime)\n",
    "\n",
    "print('普通网虫:')\n",
    "for name, onlineTime in noPass.items(): # 遍历普通网虫网名\n",
    "    print(name, onlineTime) # 通过网名输出网名和成绩"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "28d65b68",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入的乘法不在九九乘法表中\n"
     ]
    }
   ],
   "source": [
    "# 6. 99乘法表\n",
    "ninenine = dict()\n",
    "for i in range(1, 10):\n",
    "    for j in range(1, 10):\n",
    "        ninenine[\"{}*{}\".format(i,j)] = i * j # 存入字典\n",
    "#print(ninenine)\n",
    "key = input()\n",
    "if key in ninenine.keys():\n",
    "    val = ninenine[key]\n",
    "    print(val)\n",
    "    \n",
    "else:\n",
    "    print ('输入的乘法不在九九乘法表中')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7dc1381f",
   "metadata": {},
   "source": [
    "统计字符频次并创建字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "01141a4b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'f': 1, 'b': 2, 'a': 2, 'h': 2, 'l': 1, 'k': 2, 'v': 2, 'r': 2, 'n': 2, 'u': 1, 'e': 1, 'q': 1, 'i': 1, 'g': 1, 's': 1, 'c': 1}\n"
     ]
    }
   ],
   "source": [
    "str = 'fbahlkvrnueqirghbnkasvc'\n",
    "dic = dict()\n",
    "for char in str:\n",
    "    if char in dic.keys():\n",
    "        dic[char] += 1\n",
    "    else:\n",
    "        dic[char] = 1\n",
    "print(dic)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
